﻿using Kinlo.Entitys;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using XingLucifer.IBase.Enums;

namespace Kinlo.MESDocking
{
    public abstract class MESInteractionBase : IMESInteraction
    {
        protected Action<string, string, string, string, string,
            long, DateTime, string, string, string> _log;
        protected Action<string, string, string> _dialog;
        protected Stopwatch _stopwatch;
        protected string _name;
        public MESInteractionBase(Action<string, string, string, string, string, long, DateTime, string, string, string> log, Action<string, string, string> dialog, string name)
        {
            _log = log;
            _dialog = dialog;
            _name = name;
            _stopwatch = new Stopwatch();
        }
        public virtual ResultTypes Interaction(string url, int timeout, int reconnect_count, DateTime dateTime, ProductionData[] production, Dictionary<string, object> parameters)
        {
            return ResultTypes.合格;

        }

        public (bool, string) Post(string parameter, string url, int outtime, int reconnect_count)
        {
            while (reconnect_count > 0)
            {
                try
                {
                    HttpWebRequest request = WebRequest.CreateHttp(url);
                    request.ContentType = "application/json";
                    request.Method = "POST";
                    request.ProtocolVersion = HttpVersion.Version11;
                    request.Timeout = outtime;
                    //Match host = Regex.Match(url, _urlRegex);
                    //request.Host = host.Value;
                    byte[] bytes = Encoding.UTF8.GetBytes(parameter);
                    request.ContentLength = bytes.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(bytes, 0, bytes.Length);
                    }
                    var response = request.GetResponse();
                    byte[] byte1 = new byte[2048];
                    int length = 0;
                    using (Stream stream = response.GetResponseStream())
                    {
                        length = stream.Read(byte1, 0, 2048);
                    }
                    return new(true, Encoding.UTF8.GetString(byte1.Take(length).ToArray()));
                }
                catch (Exception ex)
                {
                    reconnect_count--;
                    if (reconnect_count == 0)
                    {
                        return new(false, ex.ToString());
                    }
                    Thread.Sleep(1000);
                }
            }
            return new(false, "执行错误");
        }

        public (bool, string) Get(string url, int outtime, int reconnect_count)
        {
            while (reconnect_count > 0)
            {
                try
                {
                    HttpWebRequest request = WebRequest.CreateHttp(url);
                    request.ContentType = "application/json";
                    request.Method = "GET";
                    request.ProtocolVersion = HttpVersion.Version11;
                    request.Timeout = outtime;
                    var response = request.GetResponse();
                    byte[] byte1 = new byte[2048];
                    int length = 0;
                    using (Stream stream = response.GetResponseStream())
                    {
                        length = stream.Read(byte1, 0, 2048);
                    }
                    return new(true, Encoding.UTF8.GetString(byte1.Take(length).ToArray()));
                }
                catch (Exception ex)
                {
                    reconnect_count--;
                    if (reconnect_count == 0)
                    {
                        return new(false, ex.ToString());
                    }
                }
            }
            return new(false, "执行错误");
        }

        /// <summary>
        /// 接口返回解析
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public (int, string) Result_Analysis(string json)
        {
            Dictionary<string, object> result_json = JsonSerializer.Deserialize<Dictionary<string, object>>(json, HttpHelper.Options);
            if ((bool)result_json["status"] == false)
            {
                var err = JsonSerializer.Deserialize<Dictionary<string, string>>(result_json["errMessage"].ToString(), HttpHelper.Options);
                StringBuilder stringBuilder = new StringBuilder();
                foreach (var item in err)
                {
                    stringBuilder.AppendLine(item.Value);
                }
                _dialog?.Invoke(_name, result_json["errorCode"].ToString(), stringBuilder.ToString());
                if (err.ContainsKey("errorCode"))
                {
                    /*
                     ignore : 忽略错误 == 2
                    warn : 提醒，但继续执行 == 2
                    pick : 挑出，但继续执行 == 3
                    shutdown : 提醒+停机 == 4
                     */
                    int error = 0;
                    switch (err["errorCode"])
                    {
                        case "ignore":
                        case "warn":
                            error = 2;
                            break;
                        case "pick":
                            error = 3;
                            break;
                        case "shutdown":
                            error = 4;
                            break;
                    }
                    return new(error, stringBuilder.ToString());
                }
                return new(3, stringBuilder.ToString());
            }
            return new(1, "OK");
        }
    }
}
